package com.shwread.android.qysw.activity.psychological;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.GlideUtil;
import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.NewBookDetailActivity;
import com.shwread.android.qysw.bean.psychological.QuestionnaireListBean;
import com.shwread.android.qysw.bean.psychological.TwoQuestionnaireBean;
import com.shwread.android.qysw10000242.R;
import com.shwread.android.ui.customview.BannerOnClickListener;
import com.shwread.android.ui.customview.QYViewPager;
import com.shwread.android.ui.customview.ViewPagerAdapter;
import com.shwread.android.ui.widget.refresh.SuperSwipeRefreshLayout;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import logic.bean.BannerInfo;
import logic.bean.BookInfo;
import logic.constants.DefaultConsts;
import logic.util.Util;
import logic.util.Utils;
import newui.activity.BookListWebActivity;

/**
 * 心理评测首页
 */
public class EvaluatingHomeActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tvReadMoreFree;
    private TextView tvReadMoreCharge;
    private RelativeLayout rlFreeEvaluating1;
    private ImageView imgFreeEvaluating1;
    private TextView tvFreeEvaluating1;
    private RelativeLayout rlFreeEvaluating2;
    private ImageView imgFreeEvaluating2;
    private TextView tvFreeEvaluating2;
    private RelativeLayout rlChargeEvaluating1;
    private ImageView imgChargeEvaluating1;
    private TextView tvChargeEvaluating1;
    private RelativeLayout rlChargeEvaluating2;
    private ImageView imgChargeEvaluating2;
    private TextView tvChargeEvaluating2;

    private QYViewPager vpPager;
    private ViewGroup vgPoints;
    private ViewPagerAdapter pagerAdapter;
    private List<BannerInfo> banners;
    private TwoQuestionnaireBean twoQuestionnaireBean;
    private TextView tvEvaluatingType1;
    private TextView tvEvaluatingType2;
    private TextView tvEvaluatingType3;
    private TextView tvEvaluatingType4;

    private SuperSwipeRefreshLayout layoutSwipeRefresh;
    // Header View
    private ProgressBar progressBar;
    private TextView textView;
    private ImageView imageView;
    private LinearLayout llChargeTitle;
    private LinearLayout llFreeTitle;
    private Button btnBack;

    private Runnable action = new Runnable() {
        @Override
        public void run() {
            if (banners.size() > 0) {
                int currentItem = vpPager.getCurrentItem();
                currentItem++;
                if (currentItem >= pagerAdapter.getCount()) {
                    currentItem = 0;
                }
                vpPager.setCurrentItem(currentItem);
            }
            handler.postDelayed(this, DefaultConsts.BANNER_CHANGE_TIME);
        }
    };

    private Handler handler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluating_home);
        initView();
        initData();
        initListener();
        handler.removeCallbacks(action);
        handler.postDelayed(action, DefaultConsts.BANNER_CHANGE_TIME);//每3s执行一次runnable.
    }

    private void initListener() {
        btnBack.setOnClickListener(this);
        tvReadMoreFree.setOnClickListener(this);
        tvReadMoreCharge.setOnClickListener(this);
        rlFreeEvaluating1.setOnClickListener(this);
        rlFreeEvaluating2.setOnClickListener(this);
        rlChargeEvaluating1.setOnClickListener(this);
        rlChargeEvaluating2.setOnClickListener(this);
    }

    private void initData() {
        NewActionHelp.getQuestionnaireBanner(this, 7, new QryBannerListByPositionHandler());
        NewActionHelp.getTwoQuestionnaire(this, new GetTwoQuestionnaireHandler());
    }

    private void initView() {
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);

        banners = new ArrayList<>();
        HashMap<Integer, View> views = new HashMap<>();

        vpPager = (QYViewPager) findViewById(R.id.my_world_head_pager);
        tvReadMoreCharge = (TextView) findViewById(R.id.tv_read_more_charge);
        tvReadMoreFree = (TextView) findViewById(R.id.tv_read_more_free);
        llFreeTitle = (LinearLayout) findViewById(R.id.ll_free_title);
        llChargeTitle = (LinearLayout) findViewById(R.id.ll_charge_title);

        imgFreeEvaluating1 = (ImageView) findViewById(R.id.img_free_evaluating_1);
        imgFreeEvaluating2 = (ImageView) findViewById(R.id.img_free_evaluating_2);
        imgChargeEvaluating1 = (ImageView) findViewById(R.id.img_charge_evaluating_1);
        imgChargeEvaluating2 = (ImageView) findViewById(R.id.img_charge_evaluating_2);
        tvFreeEvaluating1 = (TextView) findViewById(R.id.tv_free_evaluating_1);
        tvFreeEvaluating2 = (TextView) findViewById(R.id.tv_free_evaluating_2);
        tvChargeEvaluating1 = (TextView) findViewById(R.id.tv_charge_evaluating_1);
        tvChargeEvaluating2 = (TextView) findViewById(R.id.tv_charge_evaluating_2);
        rlFreeEvaluating1 = (RelativeLayout) findViewById(R.id.rl_free_evaluating_1);
        rlFreeEvaluating2 = (RelativeLayout) findViewById(R.id.rl_free_evaluating_2);
        rlChargeEvaluating1 = (RelativeLayout) findViewById(R.id.rl_charge_evaluating_1);
        rlChargeEvaluating2 = (RelativeLayout) findViewById(R.id.rl_charge_evaluating_2);
        tvEvaluatingType1 = (TextView) findViewById(R.id.tv_evaluating_type1);
        tvEvaluatingType2 = (TextView) findViewById(R.id.tv_evaluating_type2);
        tvEvaluatingType3 = (TextView) findViewById(R.id.tv_evaluating_type3);
        tvEvaluatingType4 = (TextView) findViewById(R.id.tv_evaluating_type4);

        layoutSwipeRefresh = (SuperSwipeRefreshLayout) findViewById(R.id.layout_swipe_refresh);
        layoutSwipeRefresh.setHeaderView(createHeaderView());
        layoutSwipeRefresh.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {//下拉刷新
            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                imageView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                initData();
            }

            @Override
            public void onPullDistance(int distance) {
            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "松开刷新" : "下拉刷新");
                imageView.setVisibility(View.VISIBLE);
                imageView.setRotation(enable ? 180 : 0);
            }
        });


        vgPoints = (ViewGroup) findViewById(R.id.my_world_head_points);// banner下面的点
        LinearLayout llVp = (LinearLayout) findViewById(R.id.llVp);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) llVp.getLayoutParams();
        lp.height = DefaultConsts.BANNER_DEFAULT_HIGHT;
        lp.width = DefaultConsts.BANNER_DEFAULT_WIDTH;
        llVp.setLayoutParams(lp);

        TextView tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText("心理评测");
        ImageView ivPerson = (ImageView) findViewById(R.id.common_header_persion);
        ivPerson.setVisibility(View.GONE);
        vpPager.addOnPageChangeListener(new PagerChangeListener());
        pagerAdapter = new ViewPagerAdapter(this, views, new BannerClick());
        vpPager.setAdapter(pagerAdapter);
    }

    private View createHeaderView() {//设置头布局
        View headerView = LayoutInflater.from(layoutSwipeRefresh.getContext()).inflate(R.layout.layout_head, null);
        progressBar = (ProgressBar) headerView.findViewById(R.id.pb_view);
        textView = (TextView) headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        imageView = (ImageView) headerView.findViewById(R.id.image_view);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.drawable.xlistview_arrow);
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                finish();
                break;
            case R.id.tv_read_more_free://体验查看更多
                intent2Activity(EvaluatingFreeListActivity.class);
                break;
            case R.id.tv_read_more_charge://付费查看更多
                intent2Activity(EvaluatingChargeListActivity.class);
                break;
            case R.id.rl_free_evaluating_1:
                toEvaluatingDetail(1);
                break;
            case R.id.rl_free_evaluating_2:
                toEvaluatingDetail(2);
                break;
            case R.id.rl_charge_evaluating_1:
                toEvaluatingDetail(3);
                break;
            case R.id.rl_charge_evaluating_2:
                toEvaluatingDetail(4);
                break;
        }
    }
    protected void intent2Activity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
    }

    private void toEvaluatingDetail(int type) {
        try {
            Intent intent = new Intent(this, EvaluatingDetailActivity.class);
            switch (type) {
                case 1:
                    intent.putExtra("questionnaireId", twoQuestionnaireBean.getExperienceQuestionnaireList().get(0).getQuestionnaireId());
                    intent.putExtra("qryType", EvaluatingDetailActivity.FREE_EVALUATING);
                    break;
                case 2:
                    intent.putExtra("questionnaireId", twoQuestionnaireBean.getExperienceQuestionnaireList().get(1).getQuestionnaireId());
                    intent.putExtra("qryType", EvaluatingDetailActivity.FREE_EVALUATING);
                    break;
                case 3:
                    intent.putExtra("questionnaireId", twoQuestionnaireBean.getPayQuestionnaireList().get(0).getQuestionnaireId());
                    intent.putExtra("qryType", EvaluatingDetailActivity.PAY_EVALUATING);
                    break;
                case 4:
                    intent.putExtra("questionnaireId", twoQuestionnaireBean.getPayQuestionnaireList().get(1).getQuestionnaireId());
                    intent.putExtra("qryType", EvaluatingDetailActivity.PAY_EVALUATING);
                    break;
                default:
                    return;
            }
            startActivity(intent);
        } catch (Exception e) {
            Utils.showToast(this, "数据异常,请刷新重试");
            e.printStackTrace();
        }
    }

    /**
     * Banner点击事件
     */
    private class BannerClick implements BannerOnClickListener {
        @Override
        public void click(BannerInfo info) {
            clickBanner(info);
        }
    }

    /**
     * Banner的滚动事件
     */
    private class PagerChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int i) {
            int pageIndex = i;
            if (i == 0) {
                // 当视图在第一个时，将页面号设置为图片的最后一张。
                pageIndex = banners.size() - 2;
            } else if (i == banners.size() - 1) {
                // 当视图在最后一个是,将页面号设置为图片的第一张。
                pageIndex = 1;
            }
            if (i != pageIndex) {
                vpPager.setCurrentItem(pageIndex, false);
            }
            setViewPoint();
        }
    }

    private void initBannerView() {
        if (banners.size() == 0) {
            return;
        }
        vgPoints.removeAllViews();
        for (int i = 0; i < banners.size() - 2; i++) {
            View view = getLayoutInflater().inflate(R.layout.banner_grid_item, vgPoints, false);
            vgPoints.addView(view);
        }
        vpPager.setCurrentItem(1);
        setViewPoint();
        pagerAdapter.notifyDataSetChanged();
    }

    private void setViewPoint() {
        for (int i = 0; i < vgPoints.getChildCount(); i++) {
            View view = vgPoints.getChildAt(i);
            ImageView img = (ImageView) view.findViewById(R.id.banner_grid_item_image);

            if (i == vpPager.getCurrentItem() - 1) {
                img.setBackgroundResource(R.drawable.banner_grid_cur);
            } else {
                img.setBackgroundResource(R.drawable.banner_grid);
            }
        }
    }

    private void clickBanner(BannerInfo info) {
        switch (info.getType()) {
            case BannerInfo.TYPE_BANNER:
                break;
            case BannerInfo.TYPE_BOOKS:
                break;
            case BannerInfo.TYPE_BOOKSURL:
                List<BookInfo> list = info.getBooks();
                if (list != null && list.get(0) != null) {
                    Intent bookIntent = new Intent(this, NewBookDetailActivity.class);
                    bookIntent.putExtra("BookInfo", list.get(0));
                    startActivity(bookIntent);
                } else {
                    Util.showToast(this, "书籍已下架");
                }
                break;
            case BannerInfo.TYPE_URL:
            case BannerInfo.TYPE_INFORMATION:
                Intent webIntent = new Intent(this, BookListWebActivity.class);
                webIntent.putExtra(DefaultConsts.title_s, info.getBannerName());
                webIntent.putExtra(DefaultConsts.req_url_s, info.getContent());
                webIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(webIntent);
                break;
            case 7://跳转到详情界面
                Intent intent = new Intent(this, EvaluatingDetailActivity.class);
                intent.putExtra("questionnaireId", (int) info.getBookId());
                intent.putExtra("qryType", "n".equals(info.getIsVote())
                        ? EvaluatingDetailActivity.PAY_EVALUATING : EvaluatingDetailActivity.FREE_EVALUATING);
                startActivity(intent);
                break;
        }
    }

    private class QryBannerListByPositionHandler extends ObjectHttpResponseHandler<List<BannerInfo>> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, List<BannerInfo> infoList, String responseString) {
            banners.clear();
            if (infoList.size() <= 1) {
                banners = infoList;
            } else {
                banners.add(infoList.get(infoList.size() - 1));
                banners.addAll(infoList);
                banners.add(infoList.get(0));
            }
            if (banners.size() > 0) {
                pagerAdapter.setData(banners);
                initBannerView();
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<List<BannerInfo>>() {
            }.getType();
        }
    }

    /**
     * 评测列表
     */
    private class GetTwoQuestionnaireHandler extends ObjectHttpResponseHandler<TwoQuestionnaireBean> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            progressBar.setVisibility(View.GONE);
            layoutSwipeRefresh.setRefreshing(false);
            Log.e("sss", "失败---" + responseString);
            Utils.showToast(EvaluatingHomeActivity.this, "加载失败");
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, TwoQuestionnaireBean questionnaireBean, String responseString) {
            progressBar.setVisibility(View.GONE);
            layoutSwipeRefresh.setRefreshing(false);
            Log.e("sss", "成功---" + responseString);
            twoQuestionnaireBean = questionnaireBean;
            setData();
        }

        @Override
        public Type getType() {
            return new TypeToken<TwoQuestionnaireBean>() {
            }.getType();
        }
    }

    /**
     * 填充首页评测数据
     */
    private void setData() {
        //体验评测
        tvReadMoreFree.setVisibility(twoQuestionnaireBean.getExperienceQuestionnaireTotal() > 2 ?
                View.VISIBLE : View.GONE);
        List<QuestionnaireListBean> experienceQuestionnaireList = twoQuestionnaireBean.getExperienceQuestionnaireList();
        if (experienceQuestionnaireList != null && experienceQuestionnaireList.size() != 0) {
            rlFreeEvaluating1.setVisibility(View.VISIBLE);
            llFreeTitle.setVisibility(View.VISIBLE);
            QuestionnaireListBean bean1 = experienceQuestionnaireList.get(0);
            tvFreeEvaluating1.setText(bean1.getTitle());
            tvEvaluatingType1.setVisibility(bean1.getType() == 1 ? View.GONE : View.VISIBLE);
            GlideUtil.filletedCornerLoad(this, bean1.getImgUrl(), 8, imgFreeEvaluating1);
            if (experienceQuestionnaireList.size() > 1) {
                QuestionnaireListBean bean2 = experienceQuestionnaireList.get(1);
                tvFreeEvaluating2.setText(bean2.getTitle());
                tvEvaluatingType2.setVisibility(bean2.getType() == 1 ? View.GONE : View.VISIBLE);
                GlideUtil.filletedCornerLoad(this, bean2.getImgUrl(), 8, imgFreeEvaluating2);
                rlFreeEvaluating2.setVisibility(View.VISIBLE);
            } else {
                rlFreeEvaluating2.setVisibility(View.GONE);
            }
        } else {
            llFreeTitle.setVisibility(View.GONE);
            rlFreeEvaluating1.setVisibility(View.GONE);
            rlFreeEvaluating2.setVisibility(View.GONE);
        }

        //付费评测
        List<QuestionnaireListBean> payQuestionnaireList = twoQuestionnaireBean.getPayQuestionnaireList();
        if (payQuestionnaireList != null && payQuestionnaireList.size() != 0) {
            rlChargeEvaluating1.setVisibility(View.VISIBLE);
            llChargeTitle.setVisibility(View.VISIBLE);
            QuestionnaireListBean bean1 = payQuestionnaireList.get(0);
            tvChargeEvaluating1.setText(bean1.getTitle());
            tvEvaluatingType3.setVisibility(bean1.getType() == 1 ? View.GONE : View.VISIBLE);
            GlideUtil.filletedCornerLoad(this, bean1.getImgUrl(), 8, imgChargeEvaluating1);
            if (payQuestionnaireList.size() > 1) {
                rlChargeEvaluating2.setVisibility(View.VISIBLE);
                QuestionnaireListBean bean2 = payQuestionnaireList.get(1);
                tvChargeEvaluating2.setText(bean2.getTitle());
                tvEvaluatingType4.setVisibility(bean2.getType() == 1 ? View.GONE : View.VISIBLE);
                GlideUtil.filletedCornerLoad(this, bean2.getImgUrl(), 8, imgChargeEvaluating2);
            } else {
                rlChargeEvaluating2.setVisibility(View.GONE);
            }
        } else {
            llChargeTitle.setVisibility(View.GONE);
            rlChargeEvaluating1.setVisibility(View.GONE);
            rlChargeEvaluating2.setVisibility(View.GONE);
        }
    }
}